<template>
    <div class="treeParent">
        <div class="antdTree">
            <a-input-search v-model:value="searchValue" @change="handleSearch" style="margin-bottom: 8px"
            placeholder="Search" />
            <a-directory-tree v-if="filteredTreeData && filteredTreeData.length" :expandedKeys="expandedKeys" indent="24" :auto-expad-parent="true"
            :tree-data="filteredTreeData" @expand="onExpand" virtual
            @select="handleTreeSelect" :fieldNames="{
                title: 'name',
            }">
            <template #title="treeNode">
                    {{ treeNode.dataRef.name }}
                <span class="editIcon" @click="edit(treeNode.dataRef)" v-if="treeNode.dataRef.selectable">
                    <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 1024 1024">
                        <path fill="currentColor" fillOpacity=".15"
                            d="M761.1 288.3L687.8 215L325.1 577.6l-15.6 89l88.9-15.7z">
                        </path>
                        <path fill="currentColor"
                            d="M880 836H144c-17.7 0-32 14.3-32 32v36c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-36c0-17.7-14.3-32-32-32m-622.3-84c2 0 4-.2 6-.5L431.9 722c2-.4 3.9-1.3 5.3-2.8l423.9-423.9a9.96 9.96 0 0 0 0-14.1L694.9 114.9c-1.9-1.9-4.4-2.9-7.1-2.9s-5.2 1-7.1 2.9L256.8 538.8c-1.5 1.5-2.4 3.3-2.8 5.3l-29.5 168.2a33.5 33.5 0 0 0 9.4 29.8c6.6 6.4 14.9 9.9 23.8 9.9m67.4-174.4L687.8 215l73.3 73.3l-362.7 362.6l-88.9 15.7z">
                        </path>
                    </svg>
                </span>
                <span class="editIcon" @click.stop="editTreeHandle(treeNode.dataRef)" v-else>
                    <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 1024 1024">
                        <path fill="currentColor" fillOpacity=".15"
                            d="M761.1 288.3L687.8 215L325.1 577.6l-15.6 89l88.9-15.7z">
                        </path>
                        <path fill="currentColor"
                            d="M880 836H144c-17.7 0-32 14.3-32 32v36c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-36c0-17.7-14.3-32-32-32m-622.3-84c2 0 4-.2 6-.5L431.9 722c2-.4 3.9-1.3 5.3-2.8l423.9-423.9a9.96 9.96 0 0 0 0-14.1L694.9 114.9c-1.9-1.9-4.4-2.9-7.1-2.9s-5.2 1-7.1 2.9L256.8 538.8c-1.5 1.5-2.4 3.3-2.8 5.3l-29.5 168.2a33.5 33.5 0 0 0 9.4 29.8c6.6 6.4 14.9 9.9 23.8 9.9m67.4-174.4L687.8 215l73.3 73.3l-362.7 362.6l-88.9 15.7z">
                        </path>
                    </svg>
                </span>
                <span class="editIcon" v-if="treeNode.dataRef.type==6 && treeNode.dataRef.deviceid">
                    <svg t="1747046531116" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4608" width="1em" height="1em"><path d="M512 0C228.430769 0 0 228.430769 0 512s228.430769 512 512 512 512-228.430769 512-512S795.569231 0 512 0z m256 413.538462l-271.753846 271.753846c-7.876923 7.876923-19.692308 11.815385-31.507692 11.815384-11.815385 0-23.630769-3.938462-31.507693-11.815384l-169.353846-169.353846c-15.753846-15.753846-15.753846-47.261538 0-63.015385 15.753846-15.753846 47.261538-15.753846 63.015385 0l137.846154 137.846154 240.246153-240.246154c15.753846-15.753846 47.261538-15.753846 63.015385 0 19.692308 15.753846 19.692308 47.261538 0 63.015385z" fill="#94C86C" p-id="4609"></path></svg>
                </span>
                <a-popconfirm
                    title="确定要取消关联吗?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="cancleMappingApi(treeNode.dataRef)"
                >
                    <span @click.stop class="editIcon">
                        <svg t="1746614399558" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4280" width="1em" height="1em"><path d="M512 1024c-282.304 0-512-229.696-512-512s229.696-512 512-512 512 229.696 512 512S794.304 1024 512 1024zM512 48.768C256.576 48.768 48.768 256.576 48.768 512S256.576 975.168 512 975.168 975.168 767.424 975.168 512 767.424 48.768 512 48.768z" fill="#d81e06" p-id="4281"></path><path d="M764.8 312.256 711.68 259.136 512 458.88 312.256 259.136 259.136 312.256 458.88 512 259.136 711.68 312.256 764.8 512 565.12 711.68 764.8 764.8 711.68 565.12 512Z" fill="#d81e06" p-id="4282"></path></svg>
                    </span>
                </a-popconfirm>
                
            </template>
        </a-directory-tree>
        </div>
        

        

        <div class="basicTable">
            <BasicTable :pagination={pageSizeOptions} @register="registerTable" :rowSelection="rowSelection">
                <template #tableTitle>
                    <a-button type="primary" @click="onEdit"> 批量编辑</a-button>
                    <a-button type="primary" @click="onCancel"> 批量取消</a-button>
                </template>
                <template #action="{ record }">
                    <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
                </template>
            </BasicTable>
        </div>
        <FocPointModal :treeNode="choiseGuid" @register="registerModal" @success="handleSuccess"></FocPointModal>
        <FocDeviceModal @register="registeDevicerModal" @success="handleDeviceSuccess"></FocDeviceModal>
        <FocEditDataModal :editTree="editTree" @register="registeEditModal" @success="handleEditSuccess">
        </FocEditDataModal>
    </div>

</template>
<script lang='ts' setup>
import { computed, ref, getCurrentInstance, nextTick } from 'vue';
import { BasicTable, FormSchema, TableAction } from '/@/components/Table';
import { getSPaceTree, focDeviceList } from '@/api/sys/menu'
import { useModal } from '/@/components/Modal/src/hooks/useModal';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns } from './FocPoint.data';
import FocPointModal from './modules/FocPointModal.vue'
import { list, deleteOne, getImportUrl,cancleMapping, getExportUrl } from './FocPoint.api';
import FocDeviceModal from './modules/FocDeviceModal.vue'
import FocEditDataModal from './modules/FocEditDataModal.vue'
import { getDictItems } from '/@/utils/dict/JDictSelectUtil';
import { message } from 'ant-design-vue';

const pageSizeOptions = ['10', '20', '50', '100', '200'];
const treeData = ref<any>([])
const choiseGuid = ref<any>({});
const expandedKeys = ref<string[]>([]);
const searchValue = ref<string>('');
const autoExpandParent = ref<boolean>(true);

// 模糊搜索逻辑
const filteredTreeData = computed(() => {
  const filter = (data) => {
    return data
      .map((item) => {
        const newItem = { ...item,key:item.guid }; // 确保 key 是唯一的
        newItem.children = item.children || []; // 确保 children 是数组

        // 递归处理子节点
        if (newItem.children.length > 0) {
          const filteredChildren = filter(newItem.children);
          newItem.children = filteredChildren;
          newItem.isLeaf = filteredChildren.length === 0; // 根据子节点数量设置 isLeaf
        } else {
          newItem.isLeaf = true; // 没有子节点时标记为叶子节点
        }

        // 过滤条件
        const shouldKeep = 
          (newItem.name && newItem.name.toLowerCase().includes(searchValue.value.toLowerCase())) || 
          newItem.children.length > 0;

        return shouldKeep ? newItem : null;
      })
      .filter(Boolean); // 过滤 null 值
  };
  return filter(treeData.value);
});
// 展开节点事件
const onExpand = (keys, event) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
};
// 查找目标节点的所有祖先节点以及其子树中的所有节点（包括最深层节点）
const findAncestorsAndSubtree = (nodes, targetKey) => {
    const allKeys = new Set(); // 使用 Set 自动去重
    // 递归查找目标节点并收集所有祖先节点和子节点
    const findAndCollect = (data, path = []) => {
        for (const node of data) {
            allKeys.add(node.guid); // 将当前节点加入展开列表
            const newPath = [...path, node.guid];
            if (node.guid === targetKey && !node.isSearch) {
                // 如果找到目标节点，收集其所有子树节点
                collectSubtree(node);
            }
            if (node.children) {
                findAndCollect(node.children, newPath); // 继续递归子节点
            }
        }
    };

    // 递归收集目标节点的所有子树节点
    const collectSubtree = (node) => {
        if (node.children) {
            for (const child of node.children) {
                allKeys.add(child.guid);
                collectSubtree(child); // 递归收集子节点的子节点
            }
        }
    };

    findAndCollect(nodes);
    return Array.from(allKeys);
};

// 搜索事件
const handleSearch = () => {
    expandedKeys.value = [];
    autoExpandParent.value = true;

    // 遍历所有匹配节点，收集需要展开的节点
    filteredTreeData.value.forEach(item => {
        const keysToExpand = findAncestorsAndSubtree(treeData.value, item.key);
        expandedKeys.value.push(...keysToExpand);
    });
    if (!searchValue.value) {
        expandedKeys.value = [];
    }

    // 去重并更新
    expandedKeys.value = Array.from(new Set(expandedKeys.value));
};

const cancleMappingApi = (params:any) => {
    cancleMapping({
        id:params.id,
        type:params.type
    }).then(res=>{
        if(res == "取消成功！"){
            if(params.type === 6){
                params.roomName = "";
                params.roomid = "";
                params.deviceid = "";
                params.deviceName = "";
                params.mpDeviceType = "";
                params.mpBigType = "";
                params.mpDeviceType = "";
                cancelMappingTree(treeData.value, params.id, params)
            }
        }
    })
}
function cancelMappingTree(nodes, targetName, values) {
    // 遍历数组中的每个节点
    for (let node of nodes) {
        // 如果当前节点的名字匹配，返回当前节点
        if (node.id == targetName) {
            for (let i in nodes) {
                node[i] = values[i];
            }
            return node;
        }

        // 如果当前节点有子节点，递归搜索子节点
        if (node.children && node.children.length > 0) {
            let found = findNodeByNameAll(node.children, targetName, values);
            if (found) {
                for (let i in nodes) {
                    found[i] = values[i];
                }
                return
            }

        }
    }

    // 如果没有找到，返回null
    return null;
}
// 获取所有节点的 key（递归）
const findAllKeys = (node) => {
    let keys = [node.key || node.id];
    if (node.children) {
        keys = keys.concat(node.children.flatMap(findAllKeys));
    }
    return keys;
};
//注册model
const [registerModal, { openModal }] = useModal();
const [registeDevicerModal, { openModal: openModalDevicerModal }] = useModal();
const [registeEditModal, { openModal: openModalEditModal }] = useModal();
const searchFormSchema: FormSchema[] = [
    {
        label: '信号类型',
        field: 'pointType',
        component: 'ApiSelect',
        componentProps: {
            api: () => getDictItems('singType'),
            resultField: 'result',
            labelField: 'text',
            showSearch: true,
            valueField: 'value',
        },
    },
    {
        label: '信号名称',
        field: 'name',
        component: 'Input',
    },
    {
        label: '是否映射',
        field: 'queryType',
        component: 'Select',
        componentProps: {
        options: [
          { label: '已映射', value: 1 },
          { label: '未映射', value: 2 },
          { label: '全部', value: '' },
        ],
      },
    }
];
const onEdit = () => {
    if(!rowSelection.selectedRowKeys.length){
        message.warning('请选择一条数据')
        return
    }
    openModal(true, {
        record:{
            ids:rowSelection.selectedRowKeys,
        },
        isUpdate: true,
        showFooter: true,
    });
}
const onCancel = () => {
    if(!rowSelection.selectedRowKeys.length){
        message.warning('请选择一条数据')
        return
    }
    openModal(true, {
        record:{
            ids:rowSelection.selectedRowKeys,
            optionType:2
        },
        isUpdate: true,
        showFooter: true,
    });
}

//注册table数据
const { tableContext } = useListPage({
    tableProps: {
        api: (e) => {
            return list({
                ...e,
                parentGuid: choiseGuid.value.guid
            })
        },
        columns,
        immediate: false,
        canResize: false,
        formConfig: {
            labelWidth: 120,
            schemas: searchFormSchema,
            autoSubmitOnEnter: true,
            showAdvancedButton: true,
        },
        actionColumn: {
            width: 120,
        },
    },
    exportConfig: {
        name: "点位管理",
        url: getExportUrl,
    },
    importConfig: {
        url: getImportUrl
    },
})

const [registerTable, { reload }, { rowSelection }] = tableContext
const handleTreeSelect = (_, e) => {
    choiseGuid.value = e.node;
    reload();
}

const editTree = ref<any>({})
const edit = (record) => {
    editTree.value = record
    openModalDevicerModal(true, {
        record,
        isUpdate: true,
        showFooter: true,
    })
}
const editTreeHandle = (record) => {
    editTree.value = record
    openModalEditModal(true, {
        record,
        isUpdate: true,
        showFooter: true,
    })
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
    openModal(true, {
        record,
        isUpdate: true,
        showFooter: true,
    });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
    openModal(true, {
        record,
        isUpdate: true,
        showFooter: false,
    });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
    await deleteOne({ id: record.id }, reload);
}
function handleSuccess() {
    rowSelection.selectedRowKeys = []
    reload();
}
function findNodeByName(nodes, targetName, values) {
    // 遍历数组中的每个节点
    for (let node of nodes) {
        // 如果当前节点的名字匹配，返回当前节点
        if (node.guid === targetName) {
            return node;
        }

        // 如果当前节点有子节点，递归搜索子节点
        if (node.children && node.children.length > 0) {
            let found = findNodeByName(node.children, targetName, values);
            if (found) {
                for (let i in values) {
                    found[i] = values[i];
                    choiseGuid.value[i] = values[i];
                }
                found.isLeaf = true;
                found.selectable = true;
                return
            }

        }
    }

    // 如果没有找到，返回null
    return null;
}

function findNodeByNameAll(nodes, targetName, values) {
    // 遍历数组中的每个节点
    for (let node of nodes) {
        // 如果当前节点的名字匹配，返回当前节点
        if (node.id == targetName) {
            for (let i in values) {
                node[i] = values[i];
                choiseGuid.value[i] = values[i];
            }
            return node;
        }

        // 如果当前节点有子节点，递归搜索子节点
        if (node.children && node.children.length > 0) {
            let found = findNodeByNameAll(node.children, targetName, values);
            if (found) {
                for (let i in values) {
                    found[i] = values[i];
                    choiseGuid.value[i] = values[i];
                }
                return
            }

        }
    }

    // 如果没有找到，返回null
    return null;
}
function handleDeviceSuccess(e) {
    findNodeByName(treeData.value, e.values.guid, e.values);
}
function handleEditSuccess(e) {
    
    findNodeByNameAll(treeData.value, e.values.id, e.values)
}

/**
* 操作栏
*/
function getTableAction(record) {
    return [
        {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
        }
    ]
}
/**
  * 下拉操作栏
  */
function getDropDownAction(record) {
    return [
        {
            label: '详情',
            onClick: handleDetail.bind(null, record),
        }, {
            label: '删除',
            popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
            }
        }
    ]
}
const getSPaceTreeApi = () => {
    getSPaceTree().then(res => {
        treeData.value = res
    })
}
getSPaceTreeApi();

// const focDeviceListApi = (e: any) => {
//     if (!loadedKeys.value.includes(e.id)) {
//         loadedKeys.value.push(e.id);
//         if (!e.children || !e.children.length) {
//             focDeviceList({ parentGuid: e.guid }).then((res: any) => {
//                 findNodeByNameAll(treeData.value, e.id, {
//                     children: res.records.map(item => {
//                         return {
//                             ...item,
//                             isLeaf: true,
//                             key: item.id,
//                             selectable: true
//                         }
//                     })
//                 })
                
//                 // nextTick(() => {
//                 //     node.children = 
//                 //     treeData.value = treeData.value
//                 //     console.log(treeData.value)
//                 //     // 触发 Vue 的更新
//                 //     instance?.proxy?.$forceUpdate()
//                 // })
//             })
//         }
//     }
// }

</script>
<style lang="scss" scoped>
.treeParent {
    display: flex;
    height: 100%;
    width: 100%;
    background-color: #fff;

    .antdTree {
        width: 300px;
        min-width: 300px;
        height: calc(100vh - 120px);
        padding-top: 10px;
        overflow-y: auto;
    }

    .basicTable {
        width: calc(100% - 300px);
        overflow-x: auto;
    }

    .editIcon {
        margin-left: 10px;
    }
}
</style>
<style>

</style>
